from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from .models import OAuthQQUser
from ouath.utils import generate_access_token,check_access_token
from django.contrib.auth import login
import json,re
from django_redis import get_redis_connection
from users.models import User
from carts.utils import merge_cart_cookie_to_redis
# Create your views here.

class QQFirstView(View):
    def get(self,requset):
        next = requset.GET.get('next')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                client_secret=settings.QQ_CLIENT_SECRET,
                redirect_uri=settings.QQ_REDIRECT_URI,
                state=next,
                        )
        qq_login_url = oauth.get_qq_url()

        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'login_url':qq_login_url
        })

class QQUserView(View):
    def get(self,request):
        code = request.GET.get('code')
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=next,
        )
        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'用户code无效!'
            })
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            token = generate_access_token(openid)
            return JsonResponse({
                'code':400,
                'errmsg':'未绑定',
                'access_token':token
            })
        else:
            login(request,qq_user.user)
            response = JsonResponse({
                'code':0,
                'errmsg':'ok'
            })
            response.set_cookie('username',qq_user.user.username)
            return merge_cart_cookie_to_redis(request, qq_user.user, response)

    def post(self,request):
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        access_token = data.get('access_token')
        if not all([mobile,password,sms_code,access_token]):
            return JsonResponse({
                'code':400,
                'errmsg':'参数缺失!'
            })
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '请输入正确的手机号码'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400,
                                 'errmsg': '请输入8-20位的密码'})
        conn = get_redis_connection('verify_code')
        sms_code_from_redis = conn.get('sms_%s'%mobile)
        if not sms_code_from_redis:
            return JsonResponse({'code': 400, 'errmsg': '手机验证码过期！'})

        if sms_code != sms_code_from_redis.decode():
            return JsonResponse({'code': 400, 'errmsg': '验证码有误'})
        openid = check_access_token(access_token)
        if openid is None:
            return JsonResponse({'code': 400, 'errmsg': 'token无效！'})
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist as e:
            user = User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password
            )
            try:
                OAuthQQUser.objects.create(
                    user=user,
                    openid=openid
                )
            except Exception as e:
                return JsonResponse({
                    'code':400,
                    'errmsg':'用户绑定失败'
                })
            else:
                if not user.check_password(password):
                    return JsonResponse({
                        'code':400,
                        'errmsg':'用户名或者密码错误'
                    })
                try:
                    OAuthQQUser.objects.create(
                        user=user,
                        openid=openid
                    )
                except Exception as e:
                    return JsonResponse({
                        'code':400,
                        'errmsg':'用户绑定失败'
                    })
            login(request,user)
            response = JsonResponse({
                'code':0,
                'errmsg':'ok'
            })
            response.set_cookie('username',user.username)
            return merge_cart_cookie_to_redis(request, user, response)
